#include "Spring.h"
#include "DX11ErrorReport.h"
#include "ObjMeshManager.h"

Spring::Spring()
{
	m_k = 0;
	m_minLength = 0;
	m_maxLength = 0;
	m_naturalLength = 0;
}

Spring::Spring(float k, float minLength, float maxLength)
{
	m_k = 0;
	m_minLength = minLength;
	m_maxLength = maxLength;
	m_naturalLength = 1.0f;//(minLength + maxLength) * 0.5f;
}

void Spring::Update()
{
	// check particles
	if (m_pParticleA == nullptr || m_pParticleB == nullptr)
	{
		DX11ErrorMsg(L"Update: NULL Particles", L"Spring Class", MB_OK);
	}

	// get distance between endpoints

	// get difference between dist and natural length(x)
	D3DXVECTOR3 difference = m_pParticleA->GetPos() - m_pParticleB->GetPos();
	
	float sqLength = D3DXVec3LengthSq(&difference);
	float length = sqrtf(sqLength);
	float x = length - m_naturalLength;
	if (fabs(x) < 0.2f)
	{
		return;
	}

	// hooks law : F = -k x
	D3DXVECTOR3 force;
	D3DXVec3Normalize(&force, &difference);
	force *= -m_k * x;
	//force *= 0.9f;
	m_pParticleA->AddForce(-force);
	m_pParticleB->AddForce(force);
}

void Spring::Draw()
{
}

void Spring::SetParticles(PhysicsParticle* a, PhysicsParticle* b)
{
	m_pParticleA = a;
	m_pParticleB = b;
}

void Spring::SetParticleA(PhysicsParticle* p)
{

}

void Spring::SetParticleB(PhysicsParticle* p)
{

}
